package com.dbapp.garden.config.security;

import com.dbapp.garden.entity.SysResource;
import com.dbapp.garden.entity.SysRole;
import com.dbapp.garden.entity.SysUser;
import com.dbapp.garden.mapper.SysResourceMapper;
import com.dbapp.garden.mapper.SysRoleMapper;
import com.dbapp.garden.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author gangzi 2017-09-18
 * @Email: 1139872666@qq.com
 */
@Service
public class CustomUserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private SysResourceMapper resourcesMapper;
    @Autowired
    private SysRoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // 获取当前需要验证的用户
        SysUser users = userMapper.querySingleUser(username);
        if (users == null) {
            throw new UsernameNotFoundException(username + " not exist!");
        }
        SysRole role = roleMapper.getRoleByUserId(users.getId());
        Collection<GrantedAuthority> grantedAuths = obtionGrantedAuthorities(users);

        PermissionUser userDetail = new PermissionUser(users.getUserName(), users.getUserPassword(), true, true, true, true, grantedAuths);
        userDetail.setUid(users.getId());
        userDetail.setGardenId(role.getGardenId());
        userDetail.setPermissionCode(role.getRoleCode());
        return userDetail;
    }

    /**
     * 取得用户的权限
     */
    private Set<GrantedAuthority> obtionGrantedAuthorities(SysUser user) {
        List<SysResource> resources = resourcesMapper.getUserResources(user.getId());
        Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>();
        for (SysResource res : resources) {

            authSet.add(new SimpleGrantedAuthority("PERMISSION_" + res.getResCode()));
        }
        return authSet;
    }
}